package com.lybus.lyxackunimall.db;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商城用户服务类
 */
@Service
public class UnimallDbService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 判断电话是否存在
	 * @param phone 电话
	 * @return
	 */
	private boolean existPhone(String phone){
		SqlRowSet query = jdbcTemplate.query("select count(*) from unimall.unimall_user where phone = '" + phone + "'",
				new SqlRowSetResultSetExtractor()
		);
		query.next();
		long count = query.getLong(1);
		return count > 0;
	}

	@Transactional
	public void insertUser(String phone, Long lyxId, String password, String salt){
		if (existPhone(phone)){
			// 用户存在,直接返回
			return;
		}
		String inviteCode = genInviteCode();
		// 注册用户类型  public static final String REGISTER_USER_TYPE = "01";
		String sql = "insert into unimall.unimall_user(phone, password, login_type, balance, freeze_balance, invite_code, gmt_create, gmt_update, gmt_last_login, salt) values(" +
				"'"+phone+"', '"+password+"', 0, 0, 0, '"+inviteCode+"', sysdate(), sysdate(), sysdate(), '"+salt+"')";
		jdbcTemplate.execute(sql);
		jdbcTemplate.execute("insert into unimall.lyx_user(id, phone) values("+lyxId+", '"+phone+"')");
	}

    public String genInviteCode() {
		while (true){
			String inviteCode = RandomStringUtils.randomAlphabetic(6);
			SqlRowSet query = jdbcTemplate.query("select count(*) from unimall.unimall_user where invite_code = '" + inviteCode + "'",
					new SqlRowSetResultSetExtractor()
			);
			query.next();
			long count = query.getLong(1);
			if(count == 0L){
				return inviteCode;
			}
		}
    }

	@Transactional
	public void updateUser(String phone, Long lyxId, String password, String salt, String oldPhone) {
		boolean existOld = existPhone(oldPhone);
		boolean existNew = existPhone(phone);
		if (!existOld && !existNew){
			insertUser(phone, lyxId, password, salt);
		}else if(existOld && !existNew){
			SqlRowSet query = jdbcTemplate.query("select id from unimall.unimall_user where phone = '" + oldPhone + "'",
					new SqlRowSetResultSetExtractor());
			if(query.next()){
				long id = query.getLong(1);
				String sql = "update unimall.unimall_user set password = '"+password+"', salt = '"+salt+"', phone = '"+phone+"' where id = " + id;
				jdbcTemplate.execute(sql);
			}

		}
	}
}
